package com.zjlanyun.eplus.view.form;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.jb.barcode.BarcodeManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.utils.KeyboardUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.greendao.DBHelper;
import com.zjlanyun.eplus.greendao.IrActWindow;
import com.zjlanyun.eplus.greendao.IrModelFields;
import com.zjlanyun.eplus.greendao.IrModelFieldsDao;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.utils.ButtonUtils;
import com.zjlanyun.eplus.utils.SoundManager;
import com.zjlanyun.eplus.view.BaseActivity;
import com.zjlanyun.eplus.view.CaptureActivity;
import com.zjlanyun.eplus.view.tree.TreeAdapter;

import org.greenrobot.greendao.query.QueryBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;

public class ChoiceBill extends BaseActivity {

    @Bind(R.id.actv_key) AutoCompleteTextView actv_key;
    @Bind(R.id.btn_search) Button btn_search;
    @Bind(R.id.btn_scan) Button btn_scan;
    @Bind(R.id.lv) ListView lv;
    @Bind(R.id.srl) SwipeRefreshLayout srl;

    private Activity activity = this;
    private long act_id;
    private int page = 1;
    private boolean isLoading = true;
    private TreeAdapter treeAdapter;
    private ArrayList<HashMap<String, Object>> mList;
    private List<IrModelFields> irModelFieldsList;
    private IrActWindow irActWindow;
    private TextView footerView;
    private boolean showLoading = true;
    private JSONObject select_data; //所有列表数据
    private JSONArray choice_data; //选中的数据
    private JSONArray choice_data_keys; //选中的数据的主键值
    private String choice_primary_key;

    private BarcodeManager scanManager;
    private boolean isPDA = false;
    private SoundManager soundManager;

    public final static int REQUESTCODE_CAMERA = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choice_bill);
        initBaseView();
        initView();
        initPDA();
    }

    private void initView() {
        title.setText("选单");
        mList = new ArrayList<>();
        choice_data = new JSONArray();
        choice_data_keys = new JSONArray();

        Intent intent = getIntent();
        act_id = intent.getLongExtra("act_id", 0);

        footerView = new TextView(this);
        footerView.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
        footerView.setPadding(0, 20, 0, 20);
        footerView.setGravity(Gravity.CENTER);
        footerView.setText("没有了");


        //获取窗口视图数据
        irActWindow = DBHelper.getDaoSession(mContext).getIrActWindowDao().load(act_id);

        //获取模型内的字段
        QueryBuilder<IrModelFields> qb = DBHelper.getDaoSession(mContext).getIrModelFieldsDao().queryBuilder();
        qb.where(IrModelFieldsDao.Properties.Model_id.eq(irActWindow.getChoice_model_id()), IrModelFieldsDao.Properties.View_type.eq("tree")).orderAsc(IrModelFieldsDao.Properties.Sequence);
        irModelFieldsList = qb.list();

        //获取选单模型的主键字段
        for (int i = 0; i < irModelFieldsList.size(); i++) {
            if (irModelFieldsList.get(i).getPrimary_key()){
                choice_primary_key = irModelFieldsList.get(i).getName();
            }
        }

        treeAdapter = new TreeAdapter(mContext, mList, irModelFieldsList);
        lv.setAdapter(treeAdapter);


        //扫描
        btn_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkCameraPermission();
                } else {
                    openScan();
                }
            }
        });

        //搜索
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoading = true;
                page = 1;
                getData();
            }
        });

        //键盘搜索按钮
        actv_key.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    showLoading = true;
                    page = 1;
                    getData();
                }
                return false;
            }
        });

        //下拉刷新
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
            }
        });

        //上滑加载更多
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (lv.getLastVisiblePosition() == mList.size() - 1 && !isLoading) {
                    getData();
                }
            }
        });

        //选入数据
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < mList.size() && mList.get(position) != null && !TextUtils.isEmpty(choice_primary_key)) {
                    try {
                        choice_data.put(select_data.getJSONObject(String.valueOf(mList.get(position).get(choice_primary_key))));
                        choice_data_keys.put(String.valueOf(mList.get(position).get(choice_primary_key)));
                        mList.remove(position);
                        treeAdapter.notifyDataSetChanged();
                        ToastUtils.showShortToast("选入成功");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        //后退按钮
        ib_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });

    }

    //后退
    private void goBack(){
        KeyboardUtils.hideSoftInput(activity);
        Intent intent = getIntent();
        intent.putExtra("choice_data", choice_data.toString());
        intent.putExtra("choice_data_keys", choice_data_keys.toString());
        setResult(RESULT_OK, intent);
        finish();
    }

    //打开扫描界面扫描条形码或二维码
    private void openScan() {
        if (!ButtonUtils.isFastDoubleClick(1)) {
            if (isPDA) {
                scanManager.Barcode_Start();
            } else {
                Intent openCameraIntent = new Intent(mContext, CaptureActivity.class);
                openCameraIntent.putExtra("from", ChoiceBill.class.getName());
                startActivityForResult(openCameraIntent, REQUESTCODE_CAMERA);
            }
        }
    }

    //初始化PDA
    private void initPDA() {
        soundManager = new SoundManager(mContext);
        //判断是否为PDA
        String deviceModel = Build.MODEL;
        if (deviceModel.length() > 5) {
            if (deviceModel.substring(0, 5).equals("HT380")) {
                isPDA = true;
                scanManager = BarcodeManager.getInstance();
                scanManager.Barcode_Open(mContext, new BarcodeManager.Callback() {
                    @Override
                    public void Barcode_Read(byte[] bytes, String s, int i) {
                        soundManager.playSound();
                        getScanResult(new String(bytes));
                    }
                });
            }
        }
    }

    //获取结果
    private void getScanResult(String code) {
        actv_key.setText(code);
        page = 1;
        getData();
    }

    private void getData(){
        // 先隐藏键盘
        KeyboardUtils.hideSoftInput(activity);
        if (TextUtils.isEmpty(actv_key.getText().toString())) {
            ToastUtils.showShortToast("请输入关键词");
            srl.setRefreshing(false);
            return;
        }
        if (page == 1){
            lv.removeFooterView(footerView);
        }

        isLoading = true;
        HashMap<String, Object> param = new HashMap<>();
        param.put("act_id", act_id);
        param.put("searchValue", actv_key.getText().toString());
        param.put("page", page);
        HttpRequest httpRequest = new HttpRequest(mContext, WebApi.api(), "choiceBill", JSON.toJSONString(param), true, showLoading);
        showLoading = false;
        httpRequest.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                try {
                    if (page == 1) {
                        mList.clear();
                        select_data = new JSONObject();
                    }

                    //保存选单的数据
                    JSONObject obj = response.get().getJSONObject("data").getJSONObject("select_data");
                    Iterator it = obj.keys();
                    while (it.hasNext()) {
                        String key = (String) it.next();
                        select_data.put(key, obj.getJSONObject(key));
                    }

                    //显示选单列表
                    JSONArray list = response.get().getJSONObject("data").getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject item = list.getJSONObject(i);
                        HashMap<String, Object> map = new HashMap<>();
                        for (int j = 0; j < irModelFieldsList.size(); j++) {
                            map.put(irModelFieldsList.get(j).getName(), item.get(irModelFieldsList.get(j).getName()));
                        }
                        mList.add(map);
                    }
                    page++;
                    treeAdapter.notifyDataSetChanged();
                    srl.setRefreshing(false);
                    if (page == 2) {
                        lv.setSelection(0);
                    }
                    if (page >= response.get().getJSONObject("data").getInt("pageCount")) {
                        isLoading = true;
                        lv.addFooterView(footerView);
                    } else {
                        isLoading = false;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 检查相机权限
     */
    private void checkCameraPermission() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            openScan();
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                ToastUtils.showLongToast("请授权，否则无法扫描");
            }
            //申请权限。
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //android6.0权限检查，重新启动扫描
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openScan();
            } else {
                ToastUtils.showShortToast("拒绝授权");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_CAMERA && resultCode == RESULT_OK && data != null) {
            //扫码结果
            getScanResult(data.getStringExtra("result"));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 139 && event.getRepeatCount() == 0) {
            openScan();
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            goBack();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
